package com.lzz.bottomencapsulation.adapter;

import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;

import com.lzz.bottomencapsulation.mvp.LBMVPBaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * viewpage  嵌套fragment适配器
 */
public class FragmentAdapter2<T extends LBMVPBaseFragment> extends FragmentPagerAdapter {
    List<T> fragmentList ;
    private  FragmentManager mfragmentManager;
    public FragmentAdapter2(FragmentManager fm, String[] titles, List<T> fragmentList) {
        super(fm);
        this.titles=titles;
        this.mfragmentManager=fm;
        this.fragmentList = fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        T instantiateItem = ((T) super.instantiateItem(container, position));
        T item = fragmentList.get(position);
        if (instantiateItem == item) {
            return instantiateItem;
        } else {
            //如果集合中对应下标的fragment和fragmentManager中的对应下标的fragment对象不一致，那么就是新添加的，所以自己add进入；这里为什么不直接调用super方法呢，因为fragment的mIndex搞的鬼，以后有机会再补一补。
            mfragmentManager.beginTransaction().add(container.getId(), item).commitNowAllowingStateLoss();
            return item;
        }
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        if (titles==null) return "";
        return titles[position];
    }

    String[] titles;

    @Override
    public int getCount() {
        return fragmentList.size();
    }
    /**
     * 销毁不可见的页面
     * @param container
     * @param position
     * @param object
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        //如果getItemPosition中的值为PagerAdapter.POSITION_NONE，就执行该方法。
        if (fragmentList.contains(fragment)) {
            super.destroyItem(container, position, fragment);
            return;
        }
        //自己执行移除。因为mFragments在删除的时候就把某个fragment对象移除了，所以一般都得自己移除在fragmentManager中的该对象。
        mfragmentManager.beginTransaction().remove(fragment).commitNowAllowingStateLoss();
//        super.destroyItem(container, position, object);
    }

    @Override
    public int getItemPosition(Object object) {
        if (!((Fragment) object).isAdded() || !fragmentList.contains(object)) {
            return PagerAdapter.POSITION_NONE;
        }
        return fragmentList.indexOf(object);
    }
}
